package com.ews.auth.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ews.auth.service.StyrzService;
import com.ews.onlineexchange.model.ServiceBuyer;
import com.ews.onlineexchange.model.ServiceSupplier;
import com.ews.onlineexchange.model.User;
import com.ews.onlineexchange.service.UserService;
import com.ews.onlineexchange.shiro.OnlineExchangeRealm;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.keycloak.adapters.jaas.BearerTokenLoginModule;

import javax.inject.Inject;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : taylover
 * @date : 2020/10/12 10:29
 */
@Path("/auth")
public class SdzwAuthRest {
    private  static final String SUCCESS_CODE = "000000";
    @GET
    @Path("/resolving/{ticket}")
    @Produces( "application/json" )
    public JSONObject resolving(@PathParam("ticket") String ticket){
        JSONObject result = new JSONObject();
        try {
            String sign = StyrzService.getSign("ticketvalidate", "");
            JSONObject tokenByTicket = (JSONObject) StyrzService.getTokenByTicket(sign, ticket);
            String tokenSecret = tokenByTicket.get("data").toString();

            // 网关返回的密文对秘密解密获取token
            String tokenStr = StyrzService.getContent(tokenSecret);
            tokenStr = tokenStr.replaceAll("\\\\", "");
            tokenStr = tokenStr.replaceAll("\"\\{", "{").replaceAll("}\"", "}");
            JSONObject parse = JSON.parseObject(tokenStr);
            String retcode = parse.getString("retcode");

            if(retcode.equals(SUCCESS_CODE)){
                JSONObject dataObj = parse.getJSONObject("data");
                String token = dataObj.getString("token");
                String usertype = dataObj.getString("usertype");
                System.out.println("usertype="+usertype);
                JSONObject infoByToken = null;
                if(usertype.equals("1")){
                    //根据token获取个人信息
                    infoByToken = (JSONObject) StyrzService.getInfoByToken(sign, token);
                }else{
                    //根据token获取法人信息
                    infoByToken = (JSONObject) StyrzService.getEntepriseInfoByToken(sign, token);
                }
                String tokenInfo = infoByToken.get("data").toString();
                String info = StyrzService.getContent(tokenInfo);
                info = info.replaceAll("\\\\", "");
                info = info.replaceAll("\"\\{", "{").replaceAll("}\"", "}");
                JSONObject jsonObject = JSON.parseObject(info);
                String retcodeUserInfo = jsonObject.getString("retcode");
                if(retcodeUserInfo.equals(SUCCESS_CODE)){
                    result = (JSONObject)jsonObject.get("data");
                    result.put("retcode",SUCCESS_CODE);
                    result.put("usertype",usertype);
                }else{
                    result.put("retcode",jsonObject.getString("retcode"));
                    result.put("msg",jsonObject.getString("msg"));
                }
            }else{
                result.put("retcode",retcode);
                result.put("msg",parse.getString("msg"));
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
            result = new JSONObject();
            result.put("retcode","666666");
            result.put("msg","出现异常");
        }
        System.out.println(result);
        return result;
    }

    public JSONObject analyzeTicket(String ticket){
        JSONObject result = new JSONObject();
        try {
            String sign = StyrzService.getSign("ticketvalidate", "");
            JSONObject tokenByTicket = (JSONObject) StyrzService.getTokenByTicket(sign, ticket);
            String tokenSecret = tokenByTicket.get("data").toString();
            // 网关返回的密文对秘密解密获取token
            String tokenStr = StyrzService.getContent(tokenSecret);
            tokenStr = tokenStr.replaceAll("\\\\", "");
            tokenStr = tokenStr.replaceAll("\"\\{", "{").replaceAll("}\"", "}");
            JSONObject parse = JSON.parseObject(tokenStr);
            String retcode = parse.getString("retcode");

            if(retcode.equals(SUCCESS_CODE)){
                JSONObject dataObj = parse.getJSONObject("data");
                String token = dataObj.getString("token");
                String usertype = dataObj.getString("usertype");
                System.out.println("usertype="+usertype);
                JSONObject infoByToken = null;
                if(usertype.equals("1")){
                    //根据token获取个人信息
                    infoByToken = (JSONObject) StyrzService.getInfoByToken(sign, token);
                }else{
                    //根据token获取法人信息
                    infoByToken = (JSONObject) StyrzService.getEntepriseInfoByToken(sign, token);
                }
                String tokenInfo = infoByToken.get("data").toString();
                String info = StyrzService.getContent(tokenInfo);
                info = info.replaceAll("\\\\", "");
                info = info.replaceAll("\"\\{", "{").replaceAll("}\"", "}");
                JSONObject jsonObject = JSON.parseObject(info);
                String retcodeUserInfo = jsonObject.getString("retcode");
                if(retcodeUserInfo.equals(SUCCESS_CODE)){
                    result = (JSONObject)jsonObject.get("data");
                    result.put("retcode",SUCCESS_CODE);
                    result.put("usertype",usertype);
                }else{
                    result.put("retcode",jsonObject.getString("retcode"));
                    result.put("msg",jsonObject.getString("msg"));
                }
            }else{
                result.put("retcode",retcode);
                result.put("msg",parse.getString("msg"));
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
            result = new JSONObject();
            result.put("retcode","666666");
            result.put("msg","出现异常");
        }
        System.out.println(result);
        return result;
    }
    @Inject
    OnlineExchangeRealm onlineExchangeRealm;
    @Inject
    UserService userService;
    @GET
    @Path(("/sdzw/login/"))
    @Produces( "application/json" )
    public void sdzwLogin(@QueryParam("ticket") String ticket,
                      @Context HttpServletRequest request,
                      @Context HttpServletResponse response){
        String contextPath = request.getContextPath();
        try{
            try {
                if(StringUtils.isBlank(ticket)){
                    response.sendRedirect(contextPath + "/ticketNullError.xhtml" );
                }
                JSONObject result = analyzeTicket(ticket);
                if(result.getString("retcode").equals("666666")){
                    response.sendRedirect(contextPath + "/sdzwInterfaceError.xhtml" );
                }else if(result.getString("retcode").equals("100003")){
                    response.sendRedirect(contextPath + "/invalidTicket.xhtml" );
                }else{

                    String sdzwUsername = result.getString("loginname");
                    User user = userService.findByUsername(sdzwUsername);
                    if(user == null){
                        response.sendRedirect(contextPath + "/userNotBindedError.xhtml" );
                    }else{

                        if(StringUtils.isBlank(user.getSdzwJson())){
                            user.setSdzwJson(result.toJSONString());
                            userService.merge(user);
                        }
                        String successPage = "/manage/index.xhtml";
                        if(user instanceof ServiceBuyer)successPage = "/business/buyer/UnauditBulletinList.xhtml";
                        if(user instanceof ServiceSupplier)successPage = "/business/supplier/UnapplyTradeList.xhtml";
                        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken();
                        usernamePasswordToken.setUsername(user.getUsername());
                        usernamePasswordToken.setPassword("WnpyakA4MzA5ODk5".toCharArray());
                        org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();
                        subject.login(usernamePasswordToken);
                        userService.setLoginedUser(null);
                        response.sendRedirect(contextPath + successPage);
                    }
                }
            } catch (IncorrectCredentialsException e2 ){
                e2.printStackTrace();
                response.sendRedirect(contextPath + "/autherror.xhtml" );
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    @GET
    @Path(("/test/login/{username}/{pwd}"))
    @Produces( "application/json" )
    public void login(@PathParam("username") String username,
                      @PathParam("pwd") String pwd,
                      @Context HttpServletRequest request,
                      @Context HttpServletResponse response){
        String contextPath = request.getContextPath();
       try{
           try {
               User user = userService.findByUsername(username);
               if(user == null){
                   response.sendRedirect(contextPath + "/autherror.xhtml" );
               }else {
                   String successPage = "/manage/index.xhtml";
                   if (user instanceof ServiceBuyer) successPage = "/business/buyer/UnauditBulletinList.xhtml";
                   if (user instanceof ServiceSupplier) successPage = "/business/supplier/UnapplyTradeList.xhtml";
                   UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken();
                   usernamePasswordToken.setUsername(username);
                   usernamePasswordToken.setPassword(pwd.toCharArray());
                   org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();
                   subject.login(usernamePasswordToken);
                   userService.setLoginedUser(null);
                   response.sendRedirect(contextPath + successPage);
               }
           } catch (IncorrectCredentialsException e2 ){
               response.sendRedirect(contextPath + "/autherror.xhtml" );
           }
       }catch (IOException e){
           e.printStackTrace();
       }
    }


}
